# -*- coding: utf-8 -*-

#from django.contrib import admin
#from djapp import views
#from DBController import *
#from google.appengine.api import memcache
"""---------------------------------------"""
import logging

class SectionLevel:
    """ 
        Category is a level in some section
        Name - name of this category
        level - order of this category in section
        tags - tags of this level. 
    """
    
    def __init__(self, level, name, tags):
        self._level = level
        self._name = name
        self.tags = tuple(tags)
        
    def __getitem__(self, tag_index):
        return self.tags[tag_index]
    
    def __len__(self):
        return len(self.tags)
    
    def __iter__(self):
        return self.tags.__iter__()

    def __unicode__(self):
        return "%d.%s: %s" % (self._level, self._name, self.tags)
    
    @property
    def name(self):
        return self._name
    
    @property
    def level(self):
        return self._level



class Section:
    """ 
        Section is a part of Catalog, which has its own Levels. 
        name - name of the section.
        level - order of the section in catalog
        structure - sorted list of Level-objects by their level inside this section.
    """
    
    def __init__(self, level, name, structure = None):
        """
            Structure is a list of 
                {'level', 'name', 'structure'} 
            dictionaries, sorted by their levels, 
            where structure is a list of level's tags.
        """
        self._level = level
        self._name = name
        if structure and type(structure[0]) == dict:
            try:
                self.structure = tuple([SectionLevel(cat['level'], cat['name'], cat['structure']) for cat in structure])
            except:
                logging.error("Could not initialize self.structure", exc_info=True)
        elif structure:
            self.structure = structure
        else:
            self.structure = ()
            
    def __getitem__(self, level_index):
        return self.structure[level_index]
    
    def __len__(self):
        return len(self.structure)
    
    def __iter__(self):
        return self.structure.__iter__()
    
    def __unicode__(self):
        rslt = u'%d.%s:\n' % (self._level, self._name)
        for lvl in self.structure:
            rslt += unicode(lvl) + '\n'
        return rslt
    
    def set_structure(self, structure):
        try:
            self.structure = tuple([SectionLevel(cat['level'], cat['name'], cat['structure']) for cat in structure])
        except:
            logging.error("Could not initialize self.structure", exc_info=True)
        
    @property
    def name(self):
        return self._name
    
    @property
    def level(self):
        return self._level        

    